package
{
	import de.nulldesign.nd2d.display.Scene2D;
	
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.utils.Dictionary;

	public class NativeDepthSorter
	{
		private var m_gameObjects:Dictionary = new Dictionary(true);
		private var m_parent:IScene;
		
		public function NativeDepthSorter(scene:IScene)
		{
			m_parent = scene;
		}
		
		public function add(gameObject:GameObject, sprite:ISprite):void{
			m_gameObjects[sprite] = gameObject;
		}
		
		public function sort(sprite:ISprite):void{
			var i:int, il:int;

			var dispObject:ISprite = sprite;
			var gameObject:GameObject = m_gameObjects[sprite];
			var index:Number;
			var dispObjectToCompare:ISprite;
			var gameObjectToCompare:GameObject;
			var spotToInsert:int = 0;
			
			m_parent.removeFromScene(sprite);
			
			// binary search to make this faster
			for(i = 0, il = m_parent.getNumChildren() ; i < il; i++){
				dispObjectToCompare = m_parent.getChildSpriteAt(i);
				gameObjectToCompare = m_gameObjects[dispObjectToCompare];
				
				if(gameObject.getCenter().length < gameObjectToCompare.getCenter().length){
					spotToInsert = i;
					
				}				
			}			

			m_parent.addToSceneAt(dispObject, spotToInsert);
		}
		
	
		public function doDepthSort(gameObjects:Vector.<GameObject>):void{
			var i:int, il:int;
			var gameObject:GameObject;
			var dispObject:ISprite;
			var index:Number;
			var dispObjectToCompare:ISprite;
			var gameObjectToCompare:GameObject;
			for(i = 1, il = m_parent.getNumChildren(); i < il; i++){
				dispObject = m_parent.getChildSpriteAt(i);
				gameObject = m_gameObjects[dispObject];
				
				dispObjectToCompare = m_parent.getChildSpriteAt(i-1);
				gameObjectToCompare = m_gameObjects[dispObjectToCompare];
				
				if(gameObject.getCenter().length > gameObjectToCompare.getCenter().length){
					m_parent.swapChildrenSprites(dispObject,dispObjectToCompare);
				}	
				
			}
		}
	}
}